﻿using System;
using System.Collections.Generic;
using System.Text;

using ValidateCommon;
using System.Web;
using System.Net;
using System.IO;
using System.Xml;
using System.Globalization;
using System.Collections;

namespace RichWebServiceDll
{
    public class RichWSUrl
    {
        /// <summary>
        /// 返回信息
        /// </summary>
        public string RequestResultMessage { get; set; }

        public RichWSUrl(string strServerIp)
        {
            try
            {
                var builderWebServiceAddress = new StringBuilder();
               
                var strName = UTF8code.RepleaseDES(EncryptUtily.EncryptUtily.LoginEncrypt("CMSValidate"));
                var strPsd = UTF8code.RepleaseDES(EncryptUtily.EncryptUtily.LoginEncrypt("Validate2012.JsbRich"));
                builderWebServiceAddress.Append("http://" + strServerIp + "/IWebSewvices/GetServerIp.asmx/GetServerIp");
                builderWebServiceAddress.Append("?strValidateName=" + strName);
                builderWebServiceAddress.Append("&strValidatePsd=" + strPsd);
                var webrequest = WebRequest.Create(builderWebServiceAddress.ToString());
                var webresponse = webrequest.GetResponse();

                var stream = webresponse.GetResponseStream();
                if (stream != null)
                {
                    var sr = new StreamReader(stream, Encoding.UTF8);
                    //读取返回流
                    var xd = new XmlDocument();
                    xd.Load(sr);
                    var strresponseString = xd.ChildNodes[1].InnerText.ToString(CultureInfo.InvariantCulture);
                    var resultHashtable = AnalysisWebResponse(strresponseString);
                    RequestResultMessage = resultHashtable["RequestResultMessage"].ToString();
                }
                else
                {
                    RequestResultMessage = "未获取返回信息";
                }
            }
            catch (Exception ex)
            {
                throw new Exception("提交服务器数据时异常:" + ex.Message.Replace("\r\n", ""));
            }
        }

        /// <summary>
        /// 处理返回字符数据并进行分割
        /// </summary>
        /// <param name="strWebResponse">webservice响应</param>
        /// <returns>分割后的哈希值对</returns>
        private static Hashtable AnalysisWebResponse(string strWebResponse)
        {
            var responseResult = strWebResponse.Split('_');

            var returnResult = new Hashtable();
            returnResult["RequestResultMessage"] = responseResult[0];
            return returnResult;
        }
    }
}
